import { defineStore } from 'pinia'
import { findPage } from '@/utils/common'
export const usePermissionStore = defineStore('permission', {
  state: () => ({
    accessRoutes: [],
    permissions: [],
    menus: [],
    routes: [],
  }),
  getters: {
    indexPage() {
      return findPage(this.menus)
    },
  },
  actions: {
    setPermissions({ permission = [], menu = [] }) {
      this.permissions = permission
      this.routes = menu
      this.menus = menu
        .map((item) => this.getMenuItem(item, null, item.code))
        .filter((item) => !!item)
        .sort((a, b) => a.sort - b.sort)
    },
    getMenuItem(item, parent, rootKey) {
      const route = this.generateRoute(item, parent?.key, rootKey)
      if (route?.meta?.routeFlag === 1) this.accessRoutes.push(route)
      const menuItem = {
        label: route.meta.title,
        key: route.name,
        path: route.path,
        icon: () => h('i', { class: `${route.meta.icon} iconfont text-16` }),
        order: item.sort ?? 0,
        menuFlag: route.meta.menuFlag,
        routeFlag: route.meta.routeFlag,
      }
      const children = item.children || []
      if (children.length) {
        menuItem.children = children
          .map((child) => this.getMenuItem(child, menuItem, rootKey))
          .filter((item) => !!item)
          .sort((a, b) => a.order - b.order)
        if (!menuItem.children.length) delete menuItem.children
      }
      return menuItem?.menuFlag === 1 ? menuItem : null
    },
    generateRoute(item, parentKey, rootKey) {
      return {
        name: item.code,
        path: item.path,
        component: item.component,
        meta: {
          icon: item.icon,
          title: item.name,
          parentKey,
          rootKey,
          menuFlag: item.menuFlag,
          routeFlag: item.routeFlag,
        },
      }
    },
    resetPermission() {
      this.$reset()
    },
    //js权限
    hasPermission(key) {
      return (this.permissions || []).includes(key)
    },
  },
})
